<template>
  <div>
    <van-popup class="tw-popup-login" v-model="innerVisible" round position="bottom" >
      <div class="tw-popup-content">
        <div class="tw-loginmodal-header" v-if="!$app.localVersion">
          <div class="tw-loginmodal-header-title">{{needDoubleAuth?'双因子验证':'登录'}}</div>
          <div class="text-link" @click="changeLoginType" v-if="!needDoubleAuth">{{loginByMobile?'账号登录':'手机号登录'}}</div>
          <div class="text-link" @click="changeValidType(validateType)" v-else>{{validateType==='mobile'?'手机验证':'邮箱验证'}}</div>
        </div>
        <div class="tw-loginmodal-header" v-else>
          <div class="tw-loginmodal-header-title">{{'登录'}}</div>
        </div>
        <!-- <div class="tw-loginmodal-header-tips">未注册的手机号验证后登录</div> -->
        <div class="tw-vant-from mt-tiny" v-if="needDoubleAuth">
          <van-form @submit="login">
            <van-field v-if="loginForm.loginStep===0"
              v-model="loginForm.loginName"
              type="text"
              name="用户名"
              :placeholder="validateType==='mobile'?'请输入验证手机':'请输入验证邮箱'"
              autocomplete="off"
              clearable
            />
            <div class="tw-validatecode-input mt-tiny" v-show="loginForm.loginStep===1"
              ref="codes">
              <input type="number"
                v-model="loginForm.yzm1"
                maxlength="1"
                @input="doYzm(1)"
                @keyup.delete="delYzm(1)" />
              <input type="number"
                v-model="loginForm.yzm2"
                maxlength="1"
                @input="doYzm(2)"
                @keyup.delete="delYzm(2)" />
              <input type="number"
                v-model="loginForm.yzm3"
                maxlength="1"
                @input="doYzm(3)"
                @keyup.delete="delYzm(3)" />
              <input type="number"
                v-model="loginForm.yzm4"
                maxlength="1"
                @input="doYzm(4)"
                @keyup.delete="delYzm(4)" />
              <input type="number"
                v-model="loginForm.yzm5"
                maxlength="1"
                @input="doYzm(5)"
                @keyup.delete="delYzm(5)" />
              <input type="number"
                v-model="loginForm.yzm6"
                maxlength="1"
                @input="doYzm(6)"
                @keyup.delete="delYzm(6)" />
            </div>
            <div class="tw-validatecode-timer" v-show="loginForm.loginStep===1">
              <a class="text-link" v-if="showGetCode"
                type="primary"
                id="login-by-phone-getcode"
                @click="sendCode()">发送验证码</a>
              <span v-else>验证码已发送，等待{{countDownTimes}}s后重新发送</span>
            </div>
          </van-form>
          <div class="mt-tiny">
            <div class="tw-button" @click="handleValidate">
              {{loginForm.loginStep===0?'下一步':'验证'}}
            </div>
          </div>
          <div class="mb-medium">&nbsp;</div>
        </div>
        <div class="tw-vant-from mt-tiny" :class="$app.localVersion?'mb-medium':''" v-else>
          <van-form @submit="login" v-if="!loginByMobile">
            <van-field
              v-model="loginForm.loginName"
              type="text"
              name="用户名"
              placeholder="请输入您的账号"
              autocomplete="off"
              clearable
            />
            <van-field
              :key="loginForm.pwdKey"
              ref="pwd-input"
              v-model="loginForm.password"
              :show-password="loginForm.showPwd"
              :type="loginForm.pwdType"
              name="密码"
              placeholder="请输入登录密码"
              autocomplete="new-password"
              clearable>
              <template v-slot:right-icon>
                <span class="solts" id="login-change-type" @click="switchPwdType">
                  <van-icon name="eye" v-if="loginForm.pwdType==='text'" />
                  <van-icon name="closed-eye" v-else />
                </span>
              </template>
            </van-field>
            <div class="tw-vant-from-captcha" v-if="captchaVisibale">
            <van-field class="xcaptcha"
              v-model="loginForm.captchaText"
              type="text"
              name="用户名"
              placeholder="请输入验证码"
              autocomplete="off"
              clearable
            />
            <img v-if="verifyCodeType === 'eco' &&
                $api.login.captchaView.data.base64Img
                " :src="$api.login.captchaView.data.base64Img" alt="验证码" title="点刷新验证码"
                @click="$api.login.captchaView.send()" />

              <div v-if="verifyCodeType === 'local'" id="vcode" class="tw-login-verifycodebox"></div>
          </div>
          </van-form>
          <van-form @submit="login" v-else>
            <van-field v-if="loginForm.loginStep===0"
              v-model="loginForm.loginName"
              type="text"
              name="用户名"
              placeholder="请输入手机号"
              autocomplete="off"
              clearable
            />
            <div class="tw-validatecode-input mt-tiny" v-show="loginForm.loginStep===1"
              ref="codes">
              <input type="number"
                v-model="loginForm.yzm1"
                maxlength="1"
                @input="doYzm(1)"
                @keyup.delete="delYzm(1)" />
              <input type="number"
                v-model="loginForm.yzm2"
                maxlength="1"
                @input="doYzm(2)"
                @keyup.delete="delYzm(2)" />
              <input type="number"
                v-model="loginForm.yzm3"
                maxlength="1"
                @input="doYzm(3)"
                @keyup.delete="delYzm(3)" />
              <input type="number"
                v-model="loginForm.yzm4"
                maxlength="1"
                @input="doYzm(4)"
                @keyup.delete="delYzm(4)" />
              <input type="number"
                v-model="loginForm.yzm5"
                maxlength="1"
                @input="doYzm(5)"
                @keyup.delete="delYzm(5)" />
              <input type="number"
                v-model="loginForm.yzm6"
                maxlength="1"
                @input="doYzm(6)"
                @keyup.delete="delYzm(6)" />
            </div>
            <div class="tw-validatecode-timer" v-show="loginForm.loginStep===1">
              <a class="text-link" v-if="showGetCode"
                type="primary"
                id="login-by-phone-getcode"
                @click="sendValidateCode()">发送验证码</a>
              <span v-else>验证码已发送，等待{{countDownTimes}}s后重新发送</span>
            </div>
          </van-form>
          <div class="mt-tiny" style="padding: 10px;border: 1px solid #ddd;border-radius: 8px;"
          v-if="loginForm.orgList.length > 0">
            <div class="tw-loginmodal-header-tips">请选择机构</div>
            <van-radio-group v-model="loginForm.uid">
              <van-cell-group v-for="user in loginForm.orgList" :key="user.userId">
                <van-cell :title="user.orgName" clickable @click="loginForm.uid = user.userId">
                  <template #right-icon>
                    <van-radio :name="user.userId" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </div>
          <div class="mt-tiny">
            <div class="tw-button" @click="handleSubmit">
              {{loginByMobile&&loginForm.loginStep===0?'下一步':'登录'}}
            </div>
          </div>
          <!-- <div class="mt-tiny" style="display: flex;visibility: hidden;">
            <van-checkbox v-model="loginForm.checked"></van-checkbox>
            我已阅读并同意<a class="text-link">《服务条款》</a>
          </div> -->

          <div class="mt-tiny" style="text-align: center;" v-if="weChat&&!$app.localVersion">
            <img @click="LoginThirdPart('1')"
             style="width: 80px;" src="@images/wx.png" alt="">
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import GVerify from '../Login/gVerify'

export default {
  data () {
    return {
      verifyCodeType: 'local',
      captchaVisibale: false,
      loginByMobile: false, // 手机登录

      isCutDown: false,
      countDownTimes: 60,
      timer: null,

      captchaCode: null,
      loginErrorFlag: false,
      sendSuccess: false,

      superAdmin: false, // 超級管理員
      needDoubleAuth: false, // 是否需要双因子验证
      validateType: 'mobile',
      showGetCode: true,

      loginForm: {
        userId: '',
        orgId: '',
        roleId: '',
        orgList: [],
        loginName: '',
        password: '',
        yzm1: '',
        yzm2: '',
        yzm3: '',
        yzm4: '',
        yzm5: '',
        yzm6: '',
        validateCode: '',

        showPwd: false,
        pwdType: 'password',
        pwdKey: 0,
        checked: true,
        loginStep: 0
      },

      userInfo: null,
      appId: '',
      appSecret: '',
      wechat: false,
      loginThirdParams: {}
    }
  },
  props: {
    visible: Boolean
  },
  computed: {
    innerVisible: {
      get () {
        return this.visible
      },
      set (val) {
        return this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    innerVisible () {
      if (this.captchaVisibale) {
        if (this.verifyCodeType === 'eco') {
          this.$api.login.captchaView.send()
        } else {
          this.genrateVerifyCode && this.genrateVerifyCode()
        }
      }
      this.needDoubleAuth = false // 是否需要双因子验证
      this.loginByMobile = false
      this.captchaVisibale = false
      this.userInfo = null
      this.showGetCode = true
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  },
  created () {
    this.getThirdLoginTypes()
  },
  methods: {
    LoginThirdPart (type) {
      let vm = this
      let appId = ''
      let redictUrl = ''
      let state = ''
      let href = ''
      let value = vm.loginThirdParams
      if (value.redirectUrl) {
        redictUrl = value.redirectUrl
      }
      if (value.state) {
        state = value.state
      }
      if (type === '1' || type === '2') {
        if (value.appId) {
          appId = value.appId
        }
      }
      if ((appId && appId === '') || (redictUrl && redictUrl === '')) {
        if (['1', '2', '3'].includes(type) && state && state === '') {
          vm.loginErrorFlag = true
          vm.loginErrorMsg = '配置参数不对'
        }
      }
      vm.appId =
        vm.$ui.cookie.get('client_id') ||
        window.$ui.urlQuery.client_id ||
        window.$app.appId
      redictUrl = encodeURIComponent(
        redictUrl +
        '&bindType=' +
        type +
        '&redirectType=1&ecoappid=' +
        window.$app.appId +
        '&urlBindCode=third_bind_redirect_uri'

        // '4b95db04975a47ec8591a0285dec2639' // vm.appId 这是新增加的应用，写死，避免与旧的冲突
      )
      if (type === '1') {
        href =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
          appId +
          '&redirect_uri=' +
          redictUrl +
          '&response_type=code&scope=snsapi_userinfo&state=' +
          state + '#wechat_redirect'
      }
      if (['1', '2', '3'].includes(type)) {
        // href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx521188588bbe75df&redirect_uri=http%3A%2F%2Fopen.teewon.net%3A9000%2Fopenapi-uc%2FwexinLogin%3Fappid%3Dwx521188588bbe75df%26env%3Decotest%26bindType%3D1%26redirectType%3D1%26ecoappid%3D4b95db04975a47ec8591a0285dec2639%26urlBindCode%3Dthird_bind_redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
        window.open(href, '_self')
      }
    },
    getThirdLoginTypes () {
      let vm = this
      this.weChat = false
      vm.$axios.get('/openapi-uc/sys/getAllowWay').then(response => {
        if (
          response.data.responseEntity &&
          response.data.responseEntity.allowLoginWay
        ) {
          let values = response.data.responseEntity.allowLoginWay.split(',')
          if (values.includes('1')) {
            this.weChat = true
            vm.loginThirdParams = response.data.responseEntity.weChat
            window.$app.setAuth({
              weChat: response.data.responseEntity.weChat
            }, true)
          }
        }
      })
    },
    /**
     * 功能: 生成前端本地验证码
     */
    genrateVerifyCode () {
      this.$nextTick(() => {
        this.verifyCode = new GVerify('vcode')
      })
    },
    handleSubmit () {
      if (this.loginByMobile && this.loginForm.loginStep === 0) {
        if (!this.loginForm.loginName) {
          this.$ui.msg({
            type: 'warning',
            message: '请输入手机号码'
          })
          return
        }
        if (!this.validatePhone()) {
          return
        }
        this.sendValidateCode().then(() => {
          if (!this.loginErrorFlag) {
            this.loginForm.loginStep = 1
          }
        })
      } else {
        if (this.loginByMobile) {
          this.showGetCode = true
          if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
            this.countDownTimes = 60
          }
        }

        this.login()
      }
    },
    changeLoginType () {
      this.loginByMobile = !this.loginByMobile
      this.resetForm()
    },
    resetForm () {
      Object.assign(this.loginForm, this.$options.data().loginForm)
      this.showGetCode = true
      this.userInfo = null
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
        this.countDownTimes = 60
      }
    },
    changeValidType (valid) {
      this.validateType = valid === 'mobile' ? 'mail' : 'mobile'
    },
    pwdInput (e) {
      if (e) {
        this.loginForm.pwdType = 'password'
        this.loginForm.showPwd = true
      } else {
        this.loginForm.pwdKey++
        this.loginForm.pwdType = 'text'
        this.loginForm.showPwd = false
        this.$nextTick(() => {
          this.$refs['pwd-input'].focus()
        })
      }
    },

    switchPwdType () {
      this.loginForm.pwdType = this.loginForm.pwdType === 'password' ? 'text' : 'password'
    },

    async sendValidateCode () {
      let vm = this

      if (!vm.validatePhone()) {
        return
      }

      vm.loginErrorFlag = false
      let req = {
        orgId: vm.loginForm.orgId ? vm.loginForm.orgId : vm.loginForm.roleId,
        to: vm.loginForm.loginName,
        toDo: 3,
        type: 1
      }
      await vm.$axios
        .post('/openapi-uc/validate/sendValidateCode', req)
        .then(response => {
          if (response.data.serverResult.resultCode === '200') {
            vm.sendSuccess = true
            vm.showGetCode = false

            if (vm.timer) {
              clearInterval(vm.timer)
            }
            vm.countDownTimes = 60
            vm.timer = setInterval(() => {
              vm.countDownTimes--
              if (vm.countDownTimes === 0) {
                vm.showGetCode = true
                clearInterval(vm.timer)
                vm.countDownTimes = 60
              }
            }, 1000)
          } else {
            vm.loginErrorFlag = false
            vm.$ui.msg({
              type: 'error',
              message: response.data.serverResult.resultMessage
            })
          }
        })
        .catch(error => {
          console.log(error)
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'error',
            message: error.data.serverResult.resultMessage
          })
          console.log(error)
        })
    },
    /***
     * 验证手机号合理性
     */
    validatePhone (loginName) {
      let vm = this
      let flag = true
      if (loginName) {
        if (!window.$ui.pattern.phone.test(loginName)) {
          flag = false
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入正确的手机号'
          })
        }
      } else {
        if (!vm.loginForm.loginName || !window.$ui.pattern.phone.test(vm.loginForm.loginName)) {
          flag = false
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入正确的手机号'
          })
        }
      }
      return flag
    },
    delYzm (type) {
      let vm = this
      let v = vm.loginForm['yzm' + type]
      if (type > 1 && !v) {
        let doms = document.getElementsByTagName('input')
        // vm['yzm' + (type - 1)] = ''
        doms[type - 2].focus()
      }
    },
    // 脱敏电话
    doYzm (type) {
      let vm = this
      let v = vm.loginForm['yzm' + type]

      if (type < 6 && v) {
        let doms = document.getElementsByTagName('input')
        // console.log(doms)
        if (v.length >= 1) {
          vm.loginForm['yzm' + type] = v.slice(0, 1)
        }
        vm.loginForm['yzm' + (type + 1)] = ''
        doms[type].focus()
      }
      let yzm = vm.loginForm.yzm1 + vm.loginForm.yzm2 + vm.loginForm.yzm3 + vm.loginForm.yzm4 + vm.loginForm.yzm5 + vm.loginForm.yzm6
      if (yzm && yzm.length === 6) {
        vm.loginForm.validateCode = yzm
      }
    },
    /***
     * 验证手机号合理性
     */
    validateEmail (loginName) {
      let vm = this
      let flag = true

      if (loginName) {
        if (!window.$ui.pattern.email.test(loginName)) {
          flag = false
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入正确的邮箱地址'
          })
        }
      } else {
        if (!vm.loginForm.loginName || !window.$ui.pattern.email.test(vm.loginForm.loginName)) {
          flag = false
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入正确的邮箱地址'
          })
        }
      }
      return flag
    },
    checkRepeat () {
      let vm = this
      vm.sendSuccess = false
      let param = vm.loginForm.loginName

      if (param !== '') {
        vm.$axios
          .post('/openapi-uc/uc/checkUserRepeat', { name: param })
          .then(response => {
            vm.superAdmin = false
            vm.loginErrorFlag = false
            if (
              response.data.pageInfo &&
              response.data.pageInfo.list.length > 0
            ) {
              response.data.pageInfo.list.forEach(el => {
                el.roleIdList.forEach(roleEl => {
                  if (roleEl === '1000000001' && roleEl.status === '1') {
                    vm.superAdmin = true
                  }
                })
              })

              vm.loginForm.orgList = []
              let userList = response.data.pageInfo.list.filter(
                item => item.status === '1'
              )
              for (let i = 0; i < userList.length; i++) {
                let u = userList[i]
                let orgObject = {}
                let roleName = ''
                let orgName = ''
                let realName = ''
                if (u.roleName) {
                  roleName = u.roleName
                }
                if (u.orgName) {
                  orgName = u.orgName
                }
                if (u.realName) {
                  realName = u.realName
                }
                orgObject.orgUserName =
                  orgName + '(' + realName + roleName + ')'
                orgObject.userId = u.userId
                orgObject.roleId = u.roleId
                orgObject.orgId = u.orgId ? u.orgId : null
                vm.loginForm.orgList.push(orgObject)
              }

              vm.loginForm.uid = userList[0].userId
              vm.loginForm.roleId = userList[0].roleId
              vm.loginForm.orgId = userList[0].orgId ? userList[0].orgId : null
            } else {
              vm.loginForm.orgList = []
              vm.loginForm.uid = null
              vm.loginForm.roleId = null
              vm.loginForm.orgId = null
            }
          })
      } else {
        vm.loginForm.orgList = []
        vm.loginForm.uid = null
        vm.loginForm.roleId = null
        vm.loginForm.orgId = null
      }
    },

    login () {
      let vm = this
      vm.appId = window.$app.appId
      vm.appSecret = window.$app.appKey
      vm.loginErrorFlag = false

      // 验证是否勾选和查看协议
      if (!vm.loginForm.checked) {
        vm.loginErrorFlag = true
        vm.$ui.msg({
          type: 'warning',
          message: '请选择协议'
        })
        return
      }

      if (this.verifyCodeType === 'eco') {
        if (
          this.$api.login.captchaView.data.base64Img &&
          !this.loginForm.captchaText
        ) {
          this.$ui.msg({ type: 'warning', message: '请输入验证码' })
          return
        } else {
          this.loginForm.captchaCode =
            this.$api.login.captchaView.data.captchaCode
        }
      } else {
        if (this.verifyCode) {
          if (this.loginForm.captchaText) {
            if (!this.verifyCode.validate(this.loginForm.captchaText)) {
              this.$ui.msg({ type: 'warning', message: '验证码错误' })
              this.loginForm.captchaText = ''
              return
            }
          } else {
            this.$ui.msg({ type: 'warning', message: '请输入验证码' })
            return
          }
        }
      }

      // 账号密码登录
      if (!vm.loginByMobile) {
        if (!vm.loginForm.loginName) {
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入用户名'
          })
          return
        }

        if (!vm.loginForm.password) {
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入密码'
          })
          return
        }
      } else {
        // 手机验证码登录
        if (!vm.validatePhone()) {
          return
        }
        if (!vm.loginForm.validateCode) {
          vm.loginErrorFlag = true
          vm.$ui.msg({
            type: 'warning',
            message: '请输入验证码'
          })
          return
        }
      }

      setTimeout(() => {
        if (!vm.loginByMobile) {
          // 对密码进行加密
          let key = vm.$ui.CryptoJS.enc.Utf8.parse(vm.appSecret)
          let encryptPassword = vm.$ui.CryptoJS.AES.encrypt(vm.loginForm.password, key, {
            mode: vm.$ui.CryptoJS.mode.ECB,
            padding: vm.$ui.CryptoJS.pad.Pkcs7
          }).toString()

          vm.userLogin(vm.loginForm.loginName, encryptPassword, '0')
        } else {
          vm.userLogin(vm.loginForm.loginName, vm.loginForm.validateCode, '0')
        }
      }, 500)
    },
    userLogin (loginName, encryptPassword, accreditCodeLogin = '0') {
      let vm = this
      vm.appId = window.$app.appId
      vm.appSecret = window.$app.appKey
      let loginParam = ''
      if (!accreditCodeLogin || accreditCodeLogin === '0') {
        loginParam =
          'client_id=' +
          vm.appId +
          '&client_secret=' +
          vm.appSecret +
          '&check_weak_pwd=1&need_update_pwd=1'
        if (!vm.loginByMobile) {
          loginParam =
            loginParam +
            '&grant_type=password&lgxm=' +
            loginName +
            '&lgmm=' +
            encodeURIComponent(encryptPassword)
          if (vm.loginForm.uid && vm.loginForm.orgList.length > 1) {
            loginParam = loginParam + '&uid=' + vm.loginForm.uid + '&version=01'
          } else {
            loginParam = loginParam + '&version=01'
          }
        } else {
          loginParam =
            loginParam +
            '&grant_type=sms_code&phone=' +
            loginName +
            '&captcha=' +
            encryptPassword
          if (vm.loginForm.uid && vm.loginForm.orgList.length > 1) {
            loginParam = loginParam + '&userId=' + vm.loginForm.uid
          }
        }

        // if (vm.captchaCode) {
        //   loginParam = loginParam + '&captchaCode=' + vm.captchaCode
        // }

        // if (vm.captcha) {
        //   loginParam = loginParam + '&captchaText=' + vm.captcha
        // }

        // 添加双因子认证参数
        let S2FACKey = vm.loginForm.loginName + '_S2FAC'
        if (vm.loginForm.uid) {
          S2FACKey = vm.loginForm.loginName + '_' + vm.loginForm.uid + '_S2FAC'
        }
        let C2FAC = localStorage.getItem(S2FACKey)
          ? localStorage.getItem(S2FACKey)
          : new Date().getTime()
        loginParam = loginParam + '&C2FAC=' + C2FAC + '&isAdmin=' + '0'
      } else {
        loginParam =
          'grant_type=client_credentials&accredit_code=' +
          accreditCodeLogin +
          '&client_id=' +
          vm.appId +
          '&client_secret=' +
          vm.appSecret
      }
      let reqAddress = window.$app.eco.gateway + '/openapi-uc/oauth/token?'
      let headConfig = {
        headers: { 'content-type': 'application/x-www-form-urlencoded' }
      }
      vm.$axios
        .post(reqAddress + loginParam, {}, headConfig)
        .then(response => {
          if (response.data.errorCode === 8008 ||
           response.data.errorCode === 8026 ||
           response.data.errorCode === 8002 ||
           response.data.errorCode === 70008) {
            vm.loginErrorFlag = true

            if (!vm.loginByMobile) {
              vm.captchaVisibale = true
              if (vm.verifyCodeType === 'eco') {
                vm.$api.login.captchaView.send()
              } else {
                vm.genrateVerifyCode && vm.genrateVerifyCode()
              }
            }
            vm.$ui.msg({
              type: 'error',
              message: response.data.errorMesage
            })
            return
          }
          let accessToken = response.data.access_token

          vm.needDoubleAuth =
            response.data && response.data.c2FARA && response.data.c2FARA === 1
          if (vm.needDoubleAuth) {
            vm.captchaVisibale = false
            Object.assign(vm.loginForm, vm.$options.data().loginForm)
            vm.showGetCode = true
            if (vm.timer) {
              clearInterval(this.timer)
              vm.timer = null
            }
          }
          vm.getUserToLogin(accessToken)
        }).catch(error => {
          let errormsg = ''
          if (!vm.loginByMobile) { // 账号密码情况下显示验证码
            vm.captchaVisibale = true
            if (vm.verifyCodeType === 'eco') {
              vm.$api.login.captchaView.send()
            } else {
              vm.genrateVerifyCode && vm.genrateVerifyCode()
            }
          }

          if (error.response.data.errorCode === 8005) {
            vm.loginForm.orgList = error.response.data.userList || []
            errormsg = '请选择机构'
          } else if (error.response.data.errorCode === 8012) {
            errormsg = '验证码错误'
          } else if (error.response.data.errorMesage) {
            errormsg = error.response.data.errorMesage
          } else {
            errormsg = '请检查账号密码或者验证码是否输入正确'
          }
          vm.$ui.msg({
            type: 'error',
            message: '登录失败，' + errormsg
          })
          vm.loginErrorFlag = true
        })
    },
    async getUserToLogin (accessToken) {
      let vm = this
      await vm.$axios
        .get('/openapi-uc/uc/getUserByToken/' + accessToken)
        .then(response => {
          let user = response.data.responseEntity
          if (!user.branchCode) {
            user.branchCode = 'twsaas'
          }
          vm.username = user.realName
          vm.orgName = user.orgName

          user.token = accessToken
          if (user) {
            if (user.roleIdList.includes(this.$cnt.ROLE_STUDENT)) {
              this.$emit('update:visible', false)
              this.$ui.msg('请使用老师账号登录')
              return
            }
            if (user.roleIdList.includes(this.$cnt.ROLE_SUPER_ADMIN) ||
                user.roleIdList.includes(this.$cnt.ROLE_REGION_ADMIN) ||
                user.roleIdList.includes(this.$cnt.ROLE_TENANT_ADMIN)) {
              window.$ui.msg('请使用老师账号登录')
              return
            }

            if (vm.needDoubleAuth) {
              vm.userInfo = user
            } else {
              // 获取菜单权限
              this.afterLogin(user, accessToken)
            }
          }
        })
        .catch(error => {
          console.log(error)
          window.$ui.msg({
            type: 'error',
            message: '获取用户信息出错'
          })
        })
    },

    async afterLogin (userInfo) {
      let vm = this
      let user = userInfo
      if (!userInfo) {
        user = vm.userInfo
      }
      // 先写入登录信息
      window.$ui.setDefaultHeaders({
        Branch_Code: user.branchCode,
        'Tenant-Id': user.branchCode,
        'Access-Token': user.token,
        'X-User-Account': user.userId,
        'Current-Org-Id': user.orgId,
        'X-User-Name': encodeURIComponent(
          user.realName || user.loginName
        ),
        'Current-Org-Name': encodeURIComponent(user.orgName),
        'Role-Id': user.role
      })

      if (user.roleIdList.includes(this.$cnt.ROLE_SCHOOL_ADMIN) ||
        user.roleIdList.includes(this.$cnt.ROLE_HEADMASTER) ||
        user.roleIdList.includes(this.$cnt.ROLE_EDU_ADMIN)) {
        user.isAdmin = true
      }

      // 应用授权给用户
      window.$app.setAuth({ ...user })

      await vm.$api.ecoOpenApi.getUserRightList
        .send({
          // 用固定appId是因为在基础数据平台，一体化菜单脚本是配置在该appId下的
          appId: window.$app.appId,
          addrType: '',
          roleId: user.roleId
        })
        .then(data => {
          window.$app.setAuth(
            {
              authList: data.list
            },
            true
          )
        })

      let baseDataApis = []

      if (user.roleIdList.includes(this.$cnt.ROLE_STUDENT) || user.roleIdList.includes(this.$cnt.ROLE_GUARDIAN)) {
        // 学生获取学生档案数据
        this.$api.ecoOpenApi.getStudentInfo.reset()
        this.$api.ecoOpenApi.getStudentInfo.params.id = user.userId
        baseDataApis.push(await this.$api.ecoOpenApi.getStudentInfo.send().then(data => {
          window.$app.setAuth({
            classId: data.classId,
            className: data.className,
            studentStatus: data.status,
            studentInfo: data
          }, true)
        }))

        // 获取学生班级数据
        this.$api.ecoOpenApi.getClass.reset()
        this.$api.ecoOpenApi.getClass.params.classId = window.$app.user.classId
        this.$api.ecoOpenApi.getClass.params.classType = this.$cnt.CLASS_TYPE_XZB
        baseDataApis.push(await this.$api.ecoOpenApi.getClass.send().then(data => {
          window.$app.setAuth({
            grade: data.grade,
            gradeName: data.gradeName,
            section: data.section,
            sectionName: data.sectionName,
            schoolType: data.schoolType,
            classStatus: data.status,
            classInfo: data
          }, true)
        }))
      }

      if (user.roleIdList.includes(this.$cnt.ROLE_TEACHER)) {
        // 老师获取任教信息
        this.$api.ecoOpenApi.queryTeachs.reset()
        this.$api.ecoOpenApi.queryTeachs.params.userId = user.userId
        baseDataApis.push(await this.$api.ecoOpenApi.queryTeachs.send().then(data => {
          window.$app.setAuth({
            teachInfo: data.list
          }, true)
        }))
      }

      this.$api.ecoOpenApi.getUserRightList.params.roleId = user.roleId
      baseDataApis.push(await this.$api.ecoOpenApi.getUserRightList.send().then(data => {
        window.$app.setAuth({
          authList: data.list
        }, true)
      }))

      Promise.all(baseDataApis).then(() => {
        this.captchaVisibale = false
        this.$emit('update:visible', false)
      })
    },

    // 双因子认证
    /***
     * 发送验证码
     */
    async sendCode () {
      let pass = true

      if (this.validateType === 'mobile') {
        pass = this.validatePhone(this.loginForm.loginName)
      } else {
        pass = this.validateEmail(this.loginForm.loginName)
      }
      if (pass) {
        this.loginErrorFlag = false
        let req = {
          address: this.loginForm.loginName,
          type: this.validateType === 'mobile' ? 0 : 1,
          userId: this.userInfo.userId
        }
        this.sending = true
        await this.$axios
          .post('/openapi-uc/f2a/sendCode', req, {
            headers: {
              'Access-Token': this.userInfo.token,
              'Tenant-Id': this.userInfo.branchCode || 'twsaas'
            }
          })
          .then(res => {
            if (res.data.serverResult.resultCode === '200') {
              let title = '发送验证码到:'
              let content = this.loginForm.loginName
              this.$ui.msg({
                message:
                  title + content + '，请注意查收！',
                type: 'success'
              })
              this.sending = false
            } else {
              this.loginErrorFlag = true
              this.$ui.msg({
                message:
                res.data.serverResult.resultMessage ||
                  '验证码发送失败',
                type: 'error'
              })
            }
          })
          .catch(error => {
            if (error.data.serverResult.resultCode === '400') {
              this.$ui.msg({
                message:
                  error.data.serverResult.resultMessage ||
                  '验证码发送失败',
                type: 'error'
              })
            }
            this.sending = false
            this.loginErrorFlag = true
            console.log(error)
          })

        this.showGetCode = false
        if (this.timer) {
          clearInterval(this.timer)
          this.countDownTimes = 60
          this.timer = null
        }
        this.timer = setInterval(() => {
          this.countDownTimes--
          if (this.countDownTimes === 0) {
            this.showGetCode = true
            clearInterval(this.timer)
            this.countDownTimes = 60
          }
        }, 1000)
      }
    },
    /**
     * 确定按钮事件
     */
    handleValidate () {
      if (this.loginForm.loginStep === 1) {
        this.ValidateHandle()
      } else {
        this.sendCode().then(() => {
          if (!this.loginErrorFlag) {
            this.loginForm.loginStep = 1
          }
        })
      }
    },
    ValidateHandle () {
      let req = {
        address: this.loginForm.loginName,
        type: this.validateType === 'mobile' ? 0 : 1,
        userId: this.userInfo.userId,
        code: this.loginForm.validateCode
      }
      this.$axios
        .post('/openapi-uc/f2a/access', req, {
          headers: {
            'Access-Token': this.userInfo.token,
            'Tenant-Id': this.userInfo.branchCode || 'twsaas'
          }
        })
        .then(res => {
          if (res.data.serverResult.resultCode === '200') {
            if (res.data.responseEntity && res.data.responseEntity.s2FAC) {
              // 将双因子信任码存入本地localstroage中
              let key =
                    this.loginForm.loginName +
                    (this.userInfo.userId ? '_' + this.userInfo.userId : '') +
                    '_S2FAC'
              localStorage.setItem(key, res.data.responseEntity.s2FAC)
            }
            this.afterLogin()

            this.showGetCode = true
            if (this.timer) {
              clearInterval(this.timer)
              this.timer = null
              this.countDownTimes = 60
            }
          } else {
            this.$ui.msg({
              message: res.data.serverResult.resultMessage,
              type: 'error'
            })
          }
        })
        .catch(error => {
          let msg = '双因子认证失败'
          if (
            error &&
                error.data &&
                error.data.serverResult &&
                error.data.serverResult.resultMessage
          ) {
            msg = error.data.serverResult.resultMessage
          }
          this.$ui.msg({
            message: msg,
            type: 'error'
          })
        })
    }
  },
  beforeUnmount () {
    let vm = this
    if (vm.timer) {
      clearInterval(vm.timer)
      vm.timer = null
    }
  }
}
</script>
<style lang="scss">
.tw-popup-login.van-popup {
  // height: 50%;

  .tw-popup-content {
    height: calc(100% - 30px);
    padding: 20px 20px 10px 10px;
    overflow-y: auto;
  }
  .tw-dialog-toolbar {
    height: 116px;
  }

  .tw-evaluate-allnode {
    height: 100%;
  }
  .tw-evaluate-allnode-child {
    height: calc(100% - 60px);

    border-top: 1px solid #E9F4FF;
    border-radius: 0 0 20px 20px;
  }
  .tw-evaluate-allnode-child-left,
  .tw-evaluate-allnode-child-right {
    height: 100%;
    overflow-y: auto;
  }

  .tw-vant-from {
    padding: 0 1.06667rem;
  }

  .tw-vant-from .van-field__body {
    height: 48px;
    line-height: 48px;
    background-color: #f2f5f7 !important;
    padding: 0 20px;
    border-radius: 8px;
  }

  .tw-vant-from .van-cell::after {
    border-bottom: none;
  }

  .tw-vant-from .van-field {
    border: none;
    padding: 0.26667rem 0;
  }

  .tw-vant-from .van-field__right-icon .van-icon {
    font-size: 22px;
  }

  .tw-vant-from .van-button--normal {
    height: 50px;
    font-size: 18px;
    width: 100%;
  }

  .tw-vant-from .xbuttonpanel {
    margin: 15px 0;
    padding: 0.26667rem 0;
  }

  .tw-vant-from .xlinkpanel {
    display: flex;
  }

  .tw-vant-from .xlinkpanel>a {
    flex: 1;
    text-align: center;
    color: #333;
  }

  .tw-validatecode-input {
    text-align: center;
    display: flex;
    justify-content: center;
  }

  .tw-validatecode-input input {
    display: inline-block;
    width: 40px;
    height: 40px;
    margin-right: 10px;
    border-radius: 4px;
    background-color: #f2f5f7;
    border: none;
    text-align: center;
    margin-bottom: 30px;
    font-size: 20px;
    font-weight: bold;
  }

  .tw-loginmodal-header {
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
  }
  .tw-loginmodal-header-title {
    font-size: 18px;
    font-weight: bold;
  }
  .tw-loginmodal-header-tips {
    padding-left: 10px;
    font-size: 14px;
    color: #999;
  }

  .tw-validatecode-timer {
    font-size: 14px;
    text-align: center;
  }

  .tw-vant-from-captcha {
    display: flex;
    align-items: center;
  }
  .tw-vant-from-captcha .xcaptcha {
    width: calc(100% - 85px);
    margin-right: 10px;
  }
  .tw-login-verifycodebox,
  .tw-vant-from-captcha > img {
    width: 80px;
    height: 40px;
  }

  .tw-login-verifycodebox {
    width: 85px;
    height: 45px;
    border-radius: 8px;
  }
}

</style>
